package com.wngbms.netty._04groupchat.server;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;

public class ChannelGroups {

    private static final ConcurrentHashMap<String, ChannelGroup> CHANNEL_GROUP_MAP = new ConcurrentHashMap<>();

    public static void add(String groupId, Channel channel) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup == null) {
            channelGroup = new DefaultChannelGroup(groupId, GlobalEventExecutor.INSTANCE);
            CHANNEL_GROUP_MAP.put(groupId, channelGroup);
        }
        channelGroup.add(channel);
    }

    public static ChannelGroup get(String groupId) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        return channelGroup;
    }

    public static ChannelGroupFuture broadCast(String groupId, Object msg) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.writeAndFlush(msg);
        }
        return null;
    }

    public static ChannelGroup flush(String groupId) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.flush();
        }
        return null;
    }

    public static boolean discard(String groupId, Channel channel) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.remove(channel);
        }
        return false;
    }

    public static ChannelGroupFuture disconnect(String groupId) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.disconnect();
        }
        return null;
    }

    public static ChannelGroupFuture disconnect(String groupId, ChannelMatcher matcher) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.disconnect(matcher);
        }
        return null;
    }

    public static boolean contains(String groupId, Channel channel) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.contains(channel);
        }
        return false;
    }

    public static int size(String groupId) {
        ChannelGroup channelGroup = CHANNEL_GROUP_MAP.get(groupId);
        if (channelGroup != null) {
            return channelGroup.size();
        }
        return 0;
    }

}
